<?php
class Pinyin{
	var $_fp  = false;
	
	function __construct() {
		$_dat = dirname(__FILE__)."/py.dat";
		if (!$this->_fp)
			$this->_fp = fopen($_dat,'rb');
	}
	
	
	
	/**
	 * return a simple instance
	 * @return 
	 */
	static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}
	function anystring2gbk($str) {
		$encode = mb_detect_encoding($str,"ASCII,UNICODE,UTF-8,GBK,CP936,EUC-CN,BIG-5,EUC-TW");
		return ($encode != 'CP936' && $encode != 'ASCII' && $encode != 'GBK' ? iconv($encode,'GBK',$str) : $str);
	}
	function get($str,$separator = ' ') {
		$str = iconv('UTF-8','GBK',$str);
		$len = strlen($str);
		
		$i = 0;$result = array();
		while ($i < $len) {
			$s = ord($str{$i});
			if ($s > 160) {
				++$i;
				if(isset($str{$i})) {
					$word = $this->word2py($s,ord($str{$i}));
				} else {
					return '';
				}
			} else {
				$word = $str{$i};
			}
			$result[] = $word;
			++$i;
		}
		return implode($separator,$result);
	}
	
	private function word2py($h,$l) {
		$high = $h - 0x81; 
		$low = $l - 0x40; 
		// 计算偏移位置
		$off = ($high<<8) + $low - ($high * 0x40);

		// 判断 off 值
		if ($off < 0) {
			return chr($h).chr($l);
		}
		fseek($this->_fp, $off * 8, SEEK_SET);
		$ret = fread($this->_fp, 8);
		if(!$ret) return '';
		$ret = unpack('a8py', $ret);
		return $ret['py'];
		
	}
	
	function __destruct() {
		if ($this->_fp)
			fclose($this->_fp);
	}
}
?>